package com.example.agriapp.view.fragment;

import static android.app.PendingIntent.getActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.fragment.app.Fragment;

import com.example.agriapp.presenter.BuyerHomeContract;
import com.example.agriapp.presenter.BuyerHomePresenter;
import com.example.agriapp.model.bean.Product;
import com.example.agriapp.R;
import com.example.agriapp.view.activity.SearchActivity;
import com.example.agriapp.adapter.ProductAdapter;
import com.google.android.material.tabs.TabLayout;

import java.util.List;

// HomeFragment.java
public class HomeFragment extends Fragment implements BuyerHomeContract.View{
    private BuyerHomePresenter presenter;
    private ProductAdapter adapter;
    private RecyclerView recyclerView;
    private SearchView searchView;
    private ProgressBar progressBar;
    private View view;

    private TabLayout tabLayout;

    public HomeFragment() {
        // Required empty public constructor
    }

    public static Fragment newInstance() {

        return new HomeFragment();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = view.findViewById(R.id.recycler_view);
        searchView = view.findViewById(R.id.search_view);
        progressBar = view.findViewById(R.id.progress_bar);
        tabLayout = view.findViewById(R.id.tabLayout);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        recyclerView.setAdapter(adapter);
        view.findViewById(R.id.tvFind).setOnClickListener(view1 -> {
            Intent intent = new Intent(getActivity(), SearchActivity.class);
            getActivity().startActivity(intent);
        });
        searchView.setOnClickListener(view1 -> {
            Intent intent = new Intent(getActivity(), SearchActivity.class);
            getActivity().startActivity(intent);
        });
        // Setup SearchView
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                presenter.searchProducts(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.isEmpty()) {
                    presenter.loadProducts();
                }
                return true;
            }
        });

        // 设置布局管理器
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));

        // 初始化Presenter
        presenter = new BuyerHomePresenter(this, getActivity());

        // 加载产品
        presenter.loadProducts();

        // 添加标签
        tabLayout.addTab(tabLayout.newTab().setText("推荐"));
        tabLayout.addTab(tabLayout.newTab().setText("水果蔬菜"));
        tabLayout.addTab(tabLayout.newTab().setText("米面粮油"));
        tabLayout.addTab(tabLayout.newTab().setText("农资农具"));

        setupTabAppearance(tabLayout);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 更新选中状态
                if (tab.getCustomView() != null) {
                    tab.getCustomView().setSelected(true);
                }

                // 根据选中的Tab加载数据
                switch (tab.getPosition()) {
                    case 0:
                       presenter.loadProducts();
                        break;
                    case 1:
                        presenter.loadProductsByCategory("水果蔬菜");
                        break;
                    case 2:
                        presenter.loadProductsByCategory("米面粮油");
                        break;
                    case 3:
                        presenter.loadProductsByCategory("农资农具");
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 更新未选中状态
                if (tab.getCustomView() != null) {
                    tab.getCustomView().setSelected(false);
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // Tab被重新选中时的处理（可选）
            }
        });
        return view;
    }

    private void setupTabAppearance(TabLayout tabLayout) {
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                TextView tabView = new TextView(getContext());
                tabView.setText(tab.getText());
                tabView.setGravity(Gravity.CENTER);
                tab.setCustomView(tabView);
            }
        }

        // 默认选中第一个Tab
        TabLayout.Tab firstTab = tabLayout.getTabAt(0);
        if (firstTab != null && firstTab.getCustomView() != null) {
            firstTab.getCustomView().setSelected(true);
        }
    }


    @Override
    public void showProducts(List<Product> products) {
        adapter = new ProductAdapter(getActivity(), products);
        Log.e("HomeFragment", "showProducts: "+products.size());
        recyclerView.setAdapter(adapter);
        recyclerView.setVisibility(View.VISIBLE);
        //emptyView.setVisibility(View.GONE);
    }

    @Override
    public void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
        //emptyView.setVisibility(View.GONE);
    }

    @Override
    public void hideLoading() {
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void showError(String message) {
//        emptyView.setText(message);
//        emptyView.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
    }

    @Override
    public void showEmptyView() {
//        emptyView.setText("没有找到商品");
//        emptyView.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
    }
}